import VueRouter from 'vue-router'
import Layout from '@/Layout'
import { $t } from '@/common/utils/i18n'

;(function () {
  // 解决vue2中router在当前页面跳转自身的报错
  const originPush = VueRouter.prototype.push
  const originReplace = VueRouter.prototype.replace
  // 给原型对象上的push指定新函数函数
  VueRouter.prototype.push = function (location, onComplete, onAbort) {
    // 判断如果没有指定回调函数, 通过call调用源函数并使用catch来处理错误
    if (onComplete === undefined && onAbort === undefined) {
      return originPush.call(this, location, onComplete, onAbort).catch((err) => console.log(err))
    } else {
      // 如果有指定任意回调函数, 通过call调用源push函数处理
      originPush.call(this, location, onComplete, onAbort)
    }
  }
  VueRouter.prototype.replace = function (location, onComplete, onAbort) {
    if (onComplete === undefined && onAbort === undefined) {
      return originReplace.call(this, location, onComplete, onAbort).catch((err) => console.log(err))
    } else {
      originReplace.call(this, location, onComplete, onAbort)
    }
  }
})()

const defaultMeat = {
  title: '',
  order: 0,
  hideTab: false,
  icon: false
}

// 递归给所有route加上meta默认值，并按照order排序，如果component是'sub'二级菜单，则不渲染实际组件而是router-view组件
export function formatRoutes (routes) {
  routes.forEach(item => {
    if (item.component === 'Sub') item.component = { render: (e) => e('router-view') }
    if (item.component === 'Layout') item.component = Layout
    item.meta = Object.assign({}, defaultMeat, item.meta || {})
    if (item.children && item.children.length) formatRoutes(item.children)
  })
  routes.sort((prev, next) => next.meta.order - prev.meta.order)
}

// !设置首页的路径
export const HOME_PAGE = '/dashboard'

// !设置html文档title的后缀
export const SUFFIX_TITLE = $t('成本管理中心')
